<template>
  <sys-dialog
      :title="dialog.title"
      :height="dialog.height"
      :width="dialog.width"
      :visible="dialog.visible"
      @onClose="onClose"
      @onConfirm="onConfirm"
  >
    <template #content>
      <a-form>
        <!-- <a-row> 代表的是一行，横向排列，一行分为24等分 -->
        <a-row>
          <a-col :span="8">
            <a-form-item
                v-bind="validateInfos.roomId"
                :labelCol="{ style: 'width:80px;' }"
                label="教室"
            >
              <a-select
                  v-model:value="addParam.roomId"
                  show-search
                  placeholder="请选择教室"
                  style="width: 200px"
                  :options="roomOptions"
                  :filter-option="filterRoomOption"
              ></a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item
                v-bind="validateInfos.courseId"
                :labelCol="{ style: 'width:80px;' }"
                label="课程"
            >
              <a-select
                  v-model:value="addParam.courseId"
                  show-search
                  placeholder="请选择课程"
                  style="width: 200px"
                  :options="courseOptions"
                  :filter-option="filterCourseOption"
              ></a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item
                v-bind="validateInfos.teacherId"
                :labelCol="{ style: 'width:80px;' }"
                label="教师"
            >
              <a-select
                  v-model:value="addParam.teacherId"
                  show-search
                  placeholder="请选择教师"
                  style="width: 200px"
                  :options="teacherOptions"
                  :filter-option="filterTeacherOption"
              ></a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-form-item
            v-bind="validateInfos.startDate"
            :labelCol="{ style: 'width:80px;' }"
            label="上课日期"
        >
          <a-range-picker
              v-model:value="selectTime"
              format="YYYY-MM-DD"
              :placeholder="['开始时间', '结束时间']"
              @change="openChange"
          />
        </a-form-item>
        <a-form-item
            v-bind="validateInfos.weeks"
            :labelCol="{ style: 'width:80px;' }"
            label="周几上课"
        >
          <a-checkbox-group :options="weekOptions" v-model:value="addParam.weeks"></a-checkbox-group>
        </a-form-item>
        <a-row>
          <a-col :span="8">
            <a-form-item v-bind="validateInfos.beginTime" label="上课时间">
              <a-time-picker
                  :minuteStep="15"
                  @change="beginTimeChange"
                  v-model:value="beginTime1"
                  format="HH:mm"
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="课程时长">
              <a-input-number v-model:value="inputNumber"></a-input-number>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item v-bind="validateInfos.endTime" label="下课时间">
              <a-time-picker :minuteStep="15" @change="endTimeChange" v-model:value="endTime1" format="HH:mm" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </template>
  </sys-dialog>

  <a-modal v-model:visible="infoVisible" title="排课冲突" @ok="handleOk">
    <template v-for="item in infoList" key="index">
      <p class="info">{{ item }}</p>
    </template>
  </a-modal>
</template>

<script setup lang="ts">
import {ref, reactive, onMounted, computed, watch} from 'vue'
import SysDialog from "@/components/SysDialog.vue";
import useSelect from "@/composable/schedule/useSelect";
import useDialog from "@/hooks/useDialog";
import dayjs, { Dayjs } from 'dayjs'
import {message} from "ant-design-vue";
import {saveScheduleApi} from "@/api/schedule";
import {useForm} from "ant-design-vue/lib/form";

//下拉属性
const { roomOptions, teacherOptions, courseOptions, filterCourseOption, filterRoomOption, filterTeacherOption } = useSelect()

//获取弹框属性
const { dialog, onShow, onClose } = useDialog()

//排课信息占用弹出框状态
const infoVisible = ref(false)
let infoList = ref([])
const handleOk = () => {
  infoVisible.value = false
}

//定义弹框显示的方法
const show = () => {
  resetFields()
  selectTime.value = undefined
  addParam.beginTime = dayjs(beginTime1.value,"HH:mm").format("HH:mm")
  addParam.endTime = dayjs(endTime1.value,"HH:mm").format("HH:mm")
  addParam.duration = inputNumber.value
  //设置弹框属性
  dialog.title = '排课'
  dialog.height = 300;
  dialog.width = 900
  //显示弹框
  onShow()
}
//暴露出去，给外部组件使用
defineExpose({
  show
})

//表单绑定的对象
const addParam = reactive({
  courseId: '',
  teacherId: '',
  roomId: '',
  startDate: '', //开课时间
  endDate: '',//结课时间
  weeks: [1, 2, 3, 4, 5],//周几上课
  beginTime: '', //上课时间
  endTime: '',//下课时间
  duration:0
})

//表单验证规则
const rules = reactive({
  weeks: [{
    required: true,
    message: '请选择周几上课',
    trigger: 'change'
  }],
  startDate: [{
    required: true,
    message: '请选择日期',
    trigger: 'change'
  }],
  roomId: [{
    required: true,
    message: '请选择教室',
    trigger: 'change'
  }],
  teacherId: [{
    required: true,
    message: '请选择教师',
    trigger: 'change'
  }],
  courseId: [{
    required: true,
    message: '请选择课程',
    trigger: 'change'
  }],
  beginTime: [{
    required: true,
    message: '请选择上课时间',
    trigger: 'change'
  }],
  endTime: [{
    required: true,
    message: '请选择上课时间',
    trigger: 'change'
  }]
})
const { resetFields, validate, validateInfos } = useForm(addParam, rules);

//上课日期选择
const selectTime = ref<Dayjs>()
//日期选择事件回调
const openChange = (data: string, dateString: string) => {
  addParam.startDate = dateString[0];
  addParam.endDate = dateString[1];
}

const weekOptions = [
  { value: 1, label: '周一' },
  { value: 2, label: '周二' },
  { value: 3, label: '周三' },
  { value: 4, label: '周四' },
  { value: 5, label: '周五' },
  { value: 6, label: '周六' },
  { value: 7, label: '周七' }
];

//上课时间
const beginTime1 = ref(dayjs('08:00', 'HH:mm'))
//上课时间点击事件
const beginTimeChange = ()=>{
  getEndTime()
}
//课程时长
const inputNumber = ref<number>(45)

watch(inputNumber,()=>{
  getEndTime()
})
//下课时间
const endTime1 = ref()
//下课时间点击事件
const endTimeChange = ()=>{
  if (endTime1.value.$H > beginTime1.value.$H){
    inputNumber.value = Math.abs(endTime1.value.$m - beginTime1.value.$m) + 60
  }else if (endTime1.value.$H == beginTime1.value.$H){//判读结束时间的小时是否等于开始时间的小时
    //判读结束时间的分钟是否大于开始时间的分钟
   if (endTime1.value.$m > beginTime1.value.$m){
     inputNumber.value = Math.abs(endTime1.value.$m - beginTime1.value.$m)
   }else {
     message.error("结束时间不能小于开始时间",1)
     getEndTime()
   }
  }else {
    message.error("结束时间不能小于开始时间",1)
    getEndTime()
  }

}

//设置时间
const getEndTime = () => {
  //上课的时间，加上45分钟= 下课时间
  endTime1.value = dayjs(beginTime1.value, "HH:mm").add(inputNumber.value, 'minute')
  addParam.beginTime = dayjs(beginTime1.value,"HH:mm").format("HH:mm")
  addParam.endTime = dayjs(endTime1.value,"HH:mm").format("HH:mm")
  addParam.duration = inputNumber.value
}
//注册事件
const emit = defineEmits(['refreshList'])
//弹框确定
const onConfirm = async () => {
  validate().then(async () => {
    const res = await saveScheduleApi(addParam)
    if (res && res.code === 200){
      if (res && res.code === 200){
        message.success(res.msg)
      }else {
        message.error(res.msg)
      }
      emit('refreshList')
      onClose()
    }else if (res && res.code === 1001){
      infoList.value = res.data.split(",")
      infoVisible.value = true
    }
  })

}

onMounted(()=>{
  getEndTime()
})


</script>

<style scoped lang="scss">
.info{
  color: red;
}
</style>
